package com.cofi.vueelementadminserver.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author xyh
 * @date 2025-01-09
 * @description 请求拦截器
 */
@SuppressWarnings("ALL")
public class RequestLogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime", System.currentTimeMillis());
        System.out.println("<==============================RequestLogInterceptor start===============================");
        String contentType = request.getContentType();
//        System.out.println("===============================TestFilter doFilter start==================================");
        System.out.println("Request-URL:" + request.getServerName() + ":" + request.getServerPort() + request.getServletPath() );
        System.out.println("User-Agent:" + request.getHeader("User-Agent") );
        System.out.println("Request-Method:" + request.getMethod());
        System.out.println("Content-Type: " + contentType);
        this.printRequestParamDetail(request);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long startTime =(long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        System.out.println("===============================(RequestLogInterceptor end)==============================>" + (endTime - startTime) + "ms");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    public void printRequestParamDetail(HttpServletRequest request) throws IOException {
        Enumeration<String> parameterNames = request.getParameterNames();
        if(!ObjectUtils.isEmpty(request.getContentType())){
            System.out.println("param:{");
            if (request.getContentType().toLowerCase().contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
                while (parameterNames.hasMoreElements()) {
                    String key = parameterNames.nextElement();
                    String value = request.getParameter(key);
                    System.out.println("\t" + key + "=" + value);
                }
                System.out.println("}");
            }else if(request.getContentType().toLowerCase().contains(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
                Map<String,Object> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                map.keySet().forEach(key->{
                    System.out.println("\t" + key + ":" + map.get(key));
                });
            }
        }else{
            System.out.println("param:无法解析contentType");
        }
    }
}
